package cn.yuanqiao.archive.management.utils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

/**
 * <p>Title: FileUtil</p>
 * <p>Description: 文件操作工具类</p>
 * @author 
 * @date 
 */
public class FileUtil {

	/**
	 * <p>Title: copyFile</p>  
	 * <p>Description: 复制文件</p>  
	 * @param sourceFile
	 * @param targetFile
	 * @throws IOException
	 */
	public static void copyFile(File sourceFile, File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}

	/**
	 * <p>Title: copyDirectiory</p>  
	 * <p>Description: 复制文件夹</p>  
	 * @param sourceDir 源文件夹
	 * @param targetDir 目标文件夹
	 * @throws IOException
	 */
	public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
		// 新建目标目录
		(new File(targetDir)).mkdirs();
		// 获取源文件夹当前下的文件或目录
		File[] file = (new File(sourceDir)).listFiles();
		if (file == null || file.length == 0) {
			return;
		}
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				// 源文件
				File sourceFile = file[i];
				// 目标文件
				File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
				copyFile(sourceFile, targetFile);
			}
			if (file[i].isDirectory()) {
				// 准备复制的源文件夹
				String dir1 = sourceDir + "/" + file[i].getName();
				// 准备复制的目标文件夹
				String dir2 = targetDir + "/" + file[i].getName();
				copyDirectiory(dir1, dir2);
			}
		}
	}

	/**
	 * <p>Title: copyFile</p>  
	 * <p>Description: 复制文件(可指定编码)</p>  
	 * @param srcFileName
	 * @param destFileName
	 * @param srcCoding
	 * @param destCoding
	 * @throws IOException
	 */
	public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding)
			throws IOException {// 把文件转换为GBK文件
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
			char[] cbuf = new char[1024 * 5];
			int len = cbuf.length;
			int off = 0;
			int ret = 0;
			while ((ret = br.read(cbuf, off, len)) > 0) {
				off += ret;
				len -= ret;
			}
			bw.write(cbuf, 0, off);
			bw.flush();
		} finally {
			if (br != null)
				br.close();
			if (bw != null)
				bw.close();
		}
	}
	/**
	 * <p>Title: delete</p>  
	 * <p>Description: 删除指定目录下的所有文件</p>  
	 * @param filepath  需要删除的目录
	 * @throws IOException
	 */
	public static void delete(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						delete(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				} // for
			}
			f.delete();
		}
	}

	public byte[] getContent(String filePath) throws IOException {
		File file = new File(filePath);
		long fileSize = file.length();
		if (fileSize > Integer.MAX_VALUE) {
			System.out.println("file too big...");
			return null;
		}
		FileInputStream fi = new FileInputStream(file);
		byte[] buffer = new byte[(int) fileSize];
		int offset = 0;
		int numRead = 0;
		while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
			offset += numRead;
		}
		// 确保所有数据均被读取
		if (offset != buffer.length) {
			throw new IOException("Could not completely read file " + file.getName());
		}
		fi.close();
		return buffer;
	}

	/**
	 * the traditional io way
	 */
	public static byte[] toByteArray(String filename) throws IOException {
		File f = new File(filename);
		if (!f.exists()) {
			throw new FileNotFoundException(filename);
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}

	/**
	 * NIO way
	 */
	public static byte[] toByteArray2(String filename) throws IOException {
		File f = new File(filename);
		if (!f.exists()) {
			throw new FileNotFoundException(filename);
		}
		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Mapped File way MappedByteBuffer 可以在处理大文件时，提升性能
	 */
	public static byte[] toByteArray3(String filename) throws IOException {
		FileChannel fc = null;
		try {
			fc = new RandomAccessFile(filename, "r").getChannel();
			MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
			System.out.println(byteBuffer.isLoaded());
			byte[] result = new byte[(int) fc.size()];
			if (byteBuffer.remaining() > 0) {
				// System.out.println("remain");
				byteBuffer.get(result, 0, byteBuffer.remaining());
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				fc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** 1左移15位就是2的15次方 这里定义数组容量为32KB */
	public static int BUFFER_SIZE = 1 << 15;
	/**
	 * <p>Title: outPutFileToPath</p>  
	 * <p>Description: 根据路径输出文件</p>  
	 * @param in 需要输出的文件流
	 * @param path 输出文件路径
	 */
	public void outPutFileToPath(InputStream in, String path) {
		try {
			FileOutputStream fos = new FileOutputStream(path);
			byte[] buffer = new byte[BUFFER_SIZE];
			int length;// 将要读进数组的字节个数
			int readLen;// 文件剩余字节数（长度）
			int resLen = in.available();// 刚开始剩余长度就等于文件长度
			long starttime = System.currentTimeMillis();
			while (resLen > 0) {
				// 如果剩余长度比定义的数组长度长，就将length赋值为BUFFER_SIZE
				// 短的话，就赋值为剩余长度resLen
				// 这一步保证读数的准确性
				length = (resLen > BUFFER_SIZE ? BUFFER_SIZE : resLen);
				// 将输入流中的数据读进buffer数组，从下标0开始读入，读length个字节数据
				readLen = in.read(buffer, 0, length);
				// 将字节数组buffer中的数据从下标0开始写，写readLen个字节数据到指定文件
				// 这部操作保证了最后一次数据的准确性
				fos.write(buffer, 0, readLen);
				// 每读写一次，意味着剩余长度减少BUFFER_SIZE
				resLen -= BUFFER_SIZE;
			}
			long endtime = System.currentTimeMillis();
			long time = endtime - starttime;
			System.out.println("写入文件用时：" + time + "( ms )");
			in.close();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * <p>Title: deleteFileByPath</p>  
	 * <p>Description: 删除指定文件</p>  
	 * @param path 需要删除的文件(全路径+文件名) 如:D:/mnt/hdda/011/H090/HDWSP/000010116/01/A/A00001011601001.docx
	 */
	public void deleteFileByPath(String path){
		File file = new File(path);
		if (file.exists() && !file.isDirectory()) {	//文件存在且不是路径
			file.delete();	//执行删除
		}
		deleteParentFileBypath(file);
	}
	public void deleteParentFileBypath(File file){
		String filePath = file.getAbsolutePath();
		filePath = filePath.substring(0,filePath.lastIndexOf(File.separator));
		File parentFile = new File(filePath);
		if (parentFile.exists() && parentFile.isDirectory()) {// 判断是文件还是目录
			if (parentFile.listFiles().length == 0) {// 若目录下没有文件则直接删除
				System.out.println("删除文件夹"+parentFile.getAbsolutePath());
				parentFile.delete();
				deleteParentFileBypath(parentFile);
			}
		}
	}
}
